package com.jdwx.opengl;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.DatabaseErrorHandler;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.os.Build;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;
import java.util.Map;

/**
 * 数据库操作
 */
public class Db extends SQLiteOpenHelper {
    private SQLiteDatabase currentDB = null;

    public Db(@Nullable Context context){
        this(context,"testdata",null,1);

    }
    public Db(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version) {
        super(context, name, factory, version);
    }

    public Db(@Nullable Context context, @Nullable String name, @Nullable SQLiteDatabase.CursorFactory factory, int version, @Nullable DatabaseErrorHandler errorHandler) {
        super(context, name, factory, version, errorHandler);
    }

    @RequiresApi(api = Build.VERSION_CODES.P)
    public Db(@Nullable Context context, @Nullable String name, int version, @NonNull SQLiteDatabase.OpenParams openParams) {
        super(context, name, version, openParams);
    }

    //创建数据库
    @Override
    public void onCreate(SQLiteDatabase db) {

        this.currentDB = db;

        String sql = "CREATE TABLE IF NOT EXISTS "
                + "student ( "
                + " id INTEGER PRIMARY KEY AUTOINCREMENT, "
                + "name TEXT,"
                + "gender INTEGER, "
                + "number TEXT, "
                + "score INTEGER)";

        db.execSQL(sql);

    }


    /**
     * 删除所有表
     */
    public synchronized void dropAllTables() {
        SQLiteDatabase db = this.getWritableDatabase();
        if (db == null)
            return;
        Cursor cur = db.query("sqlite_master", new String[] { "name" }, "type='table'", null, null, null, null);
        while (cur.moveToNext()) {
            String name = cur.getString(0);
            if (name.equals("android_metadata"))
                continue;
            db.execSQL("DROP TABLE IF EXISTS " + name);
        }
        // db.close();
    }

    /**
     *  删除单个表
     *
     * @param tableName
     * @return
     */
    public synchronized int dropTable(String tableName) {
        if (tableName != null) {
            SQLiteDatabase db = this.getWritableDatabase();
            db.execSQL("DROP TABLE IF EXISTS " + tableName);
            db.close();
            return 1;
        }
        return 0;
    }

    /**
     * 数据库版本更新
     * @param db
     * @param oldVersion
     * @param newVersion
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        this.currentDB = db;
        if (oldVersion < newVersion) {
            dropAllTables();//删除之前的表 重新建表
            onCreate(db);
        }
    }

    @Override
    public SQLiteDatabase getWritableDatabase() {
        // TODO Auto-generated method stub
        if (currentDB != null) {
            return currentDB;
        }
        return super.getWritableDatabase();
    }

    /**
     * 数据的删除
     */
    public synchronized void delete(String tableName,String where ,String[] whereArgs) {
        try {
            SQLiteDatabase db = this.getWritableDatabase();
            db.delete(tableName, where, whereArgs);
            db.close();
        } catch (Exception ex) {

        }
    }
    public synchronized void delete2(String tableName, String where) {
        try {
            SQLiteDatabase db = this.getWritableDatabase();
            db.delete(tableName, where,null);
            db.close();
        } catch (Exception ex) {

        }
    }



    public void updateData(String sql) {
        SQLiteDatabase db = this.getWritableDatabase();
        db.execSQL( sql );
    }



    /**
     * 插入数据
     *
     * @param t
     * @return
     */
    public synchronized long insert(String tableName, Map map) {
        SQLiteDatabase db = this.getWritableDatabase();

        ContentValues contentValues = new ContentValues();
        //contentValues.put("id",(int)map.get("id"));
        contentValues.put("name",(String)map.get("name"));
        contentValues.put("gender",(int)map.get("gender"));
        contentValues.put("number",(String)map.get("number"));
        contentValues.put("score",(int)map.get("score"));

        //db.insertWithOnConflict(tableName,null,contentValues,SQLiteDatabase.CONFLICT_IGNORE);

        long insertid = db.replace(tableName, null, contentValues);

        db.close();

        return insertid;
    }
    /**
     * 查询
     * 这里直接返回游标，如果想抽象公用，直接使用反射注解等方法解析
     */
    public synchronized Cursor query(String tableName,String where,String order,int start,int count ){
        SQLiteDatabase db = this.getWritableDatabase();

        Cursor cursor = db.query(tableName, null, where, new String[] {}, null, null, order,start+","+count);
        //cursor = db.rawQuery("select *   from TableSong where Words=?",new String[]{"6"}  );
        return cursor;
    }





}
